{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Advanced Features" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Packages\n", "Packages are how we load in functionality that exists outside of the standard python library. We use Anaconda to manage these for us, in most cases.\n", "\n", "We can load packages with:\n", " - import {package_name}\n", " - import {package_name} as {new_name}\n", " - from {package_name} import {sub_module}\n", " \n", "We can also install packages later with **!pip install {package_name}** if running from within jupyter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nImporting Packages:\")\n", "import math # import command lets you load local and installed packages\n", "print(math) # math is now loaded as a variable into our enviornment\n", "print(dir(math)) # Lets take a look at what we loaded in\n", "print()\n", "print(math.pi) # With math we can access pi\n", "\n", "# We could also attempt to just load the portion of the module we are interested in\n", "from math import pi # this will load the variable pi into our enviornment\n", "print(pi)\n", "\n", "from math import pi as pie # Can also rename any \n", "print(pie)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sets\n", "A python **set** follows the same principle of a mathematics set. Meaning each object will only appear once (i.e. it deduplicates elements)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Sets - list of unique elements\n", "\n", "lst = [1,4,45,23,3,4,432,543,23,45,23,2,1]\n", "s = set(lst)\n", "print(lst)\n", "print(s)\n", "print(\"len of s - {} vs len of lst - {}\".format(len(s), len(lst)))\n", "# This makes them great for checking duplicates!\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Set differences\n", "\n", "s1 = set([1,2,3,4,5,6,7,8,9,10])\n", "s2 = set([2,5,8,9])\n", "print(f\"Elements only in s1 - {s1 - s2}\") # We are only left with the elements only in s1\n", "print(f\"Elements in s1 and s2 - {s1.intersection(s2)}\") # elements in both s1 and s2\n", "print(f\"Is s2 a subet of s1 - {s2.issubset(s1)}\") # Is s2 a subset of s1\n", "\n", "s3 = set([1,2,32,56])\n", "print(s1.symmetric_difference(s3)) #Returns elements that only appear once\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List comprehension\n", "List comprehension is a shortcut method for **for loops**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nList Comprehension:\")\n", "lst = [113, 94, 463, 432, 123.95, 394.93, 2342, 12, 5, 2.30]\n", "# With list comprehension we can alter lists inline\n", "str_lst = [str(x) for x in lst]\n", "print(str_lst)\n", "\n", "#If we want to sum the str_lst we can utlize this feature\n", "sum_str_list = sum([float(x) for x in str_lst])\n", "print(sum_str_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dict comprehension" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"**********\\nWorking With Dicts:\")\n", "#{'name': [boys, girls]}\n", "name_dict = {'Sam': [6,3], 'Alex': [4,2], 'Jack': [3,0], 'Sarah': [0,5]}\n", "\n", "sum_lst = [sum(name_dict[x]) for x in name_dict] #Can sum over elements\n", "sum_lst2 = [x+y for x,y in name_dict.values()] #We can unpack multiple elements (only works since always 2 elements)\n", "new_dict = {x:sum(name_dict[x]) for x in name_dict} #Can also do dict comprehension\n", "new_dict2 = {k:sum(v) for k,v in name_dict.items()} #Can clean it up a bit by taking key, value in comprehension\n", "\n", "print(sum_lst)\n", "print(sum_lst2)\n", "print(new_dict)\n", "print(new_dict2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Lambdas and Conditionals in comprehensions\n", "from functools import reduce\n", "\n", "name_dict = {'Sam': [6,3,4], 'Alex': [4,2,3], 'Jack': [3,0,3,2], 'Sarah': [0,5]}\n", "\n", "new_dict3 = {x:sum(y) for x,y in name_dict.items() if 'S' in x} # Can also add conditionals\n", "new_dict4 = {x:reduce(lambda a,b: a*b, y) for x,y in name_dict.items()} # Or even lambdas\n", "# Notice we need to use reduce, as there is a variable amount of values in the lists\n", "print(new_dict3)\n", "print(new_dict4)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### In class work" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Problem 1\n", "\"\"\"\n", "Using list comprehension create a list of only negative values\n", "\"\"\"\n", "lst = [34, 54, -32, 43, -2, -23, -423, -23, 342, 56]\n", "\n", "\n", "#Problem 2\n", "\"\"\"\n", "Using dict comprehension generate a dictionary of the following nature - {k:sum(v)}\n", "Ex. {'Sep': [-4, 2, 4, -1], 'Oct': [11, 4, 7, 6], 'Nov': [5, -1, 3, -3]} -> {'Sep': 2, 'Oct': 4, 'Nov': 1}\n", "\"\"\"\n", "dict = {'Sep': [-4, 2, 4, -1], 'Oct': [11, 4, 7, 6], 'Nov': [5, -1, 0, -3]}\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### PDB debugging\n", "Commands:\n", " - c - continues to end or next breakpoint\n", " - s - execute current line, stopping at next available point (stops in function calls)\n", " - n - execute until next line of code\n", " - r - continue until function returns\n", " - q/exit - quite execution\n", " - ... - more details online" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#PDB debugging\n", "\n", "import pdb\n", "\n", "pdb.set_trace() #With this statement we can put a breakpoint anywhere in our code\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Returning Multiple Values\n", "You can return tuples and capture these values in separate values simply by listing them out.\n", "\n", "*Note: you can skip a value with a __*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Returning multiple values\n", "\n", "print(\"**********\\nReturning More Than One Value:\")\n", "def return_two_vals(x, y):\n", " return (x-y, x+y)\n", "\n", "sub, add = return_two_vals(3, 5) # Comma seperated variables can capture multiple values\n", "print(\"Sub = {}, Add = {}\".format(sub, add))\n", "\n", "# What if we only want one value\n", "_, add = return_two_vals(6, 5) # an _ in the assignment operation tells python to skip that assignment\n", "print(\"Sub = {}, Add = {}\".format(sub, add)) # Notice sub does not change in value\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [default]", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" } }, "nbformat": 4, "nbformat_minor": 2 }